package com.zhb.cloud.core.distribute.lock;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.zhb.cloud.config.RedisConfig;
import com.zhb.cloud.core.distribute.redisson.lock.RedisDistributedLock;
import com.zhb.cloud.core.distribute.zookeeper.lock.ZooKeeperDistributedLock;

/**
 * @ClassName: LockFactory
 * @author: zhb
 * @date: 2017年8月4日 下午2:00:54
 * @Description: 锁工厂
 *
 */
@Component
public class LockFactory {
	@Value("${lock.sleep}")
	private int sleep;
	@Value("${lock.time}")
	private int lockTime;

	// zookeeper config
	@Value("${lock.prefix}")
	private String lockPrefix;
	@Value("${zookeeper.hosts}")
	private String zkConnectUrl;

	// redis config
	@Value("${spring.redis.host}")
	private String jedisPoolHost;
	@Value("${spring.redis.port}")
	private int jedisPoolPort;
	@Value("${spring.redis.password}")
	private String jedisPoolPassword;
	@Value("${spring.redis.timeout}")
	private int jedisPoolTimeout;

	private static RedisConfig REDIS_CONFIG;

	@PostConstruct
	public void initRedisConfig() {
		REDIS_CONFIG = new RedisConfig(jedisPoolHost, jedisPoolPort, jedisPoolPassword, jedisPoolTimeout);
	}

	/**
	 * Obtain a distribute lock.
	 *
	 * @param lockPath
	 * @return
	 */
	public DistributedLock obtainLock(String lockPath) {
		return new ZooKeeperDistributedLock(zkConnectUrl, lockPath);
	}

	/**
	 * 获取基于redis实现的分布式锁
	 * 
	 * @param lockPath
	 * @return
	 */
	public DistributedLock obtainRedisLock(String lockPath) {
		return new RedisDistributedLock(REDIS_CONFIG, lockPath);
	}

}
